﻿using TeachlyQBank.DbPool;
using TeachlyQBank.Models;
using NLog;
using System.Text.Json;
using MySqlX.XDevAPI;
using ZstdSharp.Unsafe;
using System.Data;

namespace TeachlyQBank.DbServer
{
    public class KnowledgeServer
    {
        private readonly MySqlConnectionAdapter _mysql; // 操作mysql的类
        private readonly Logger _logger;  //记录日志的类
        private readonly UserServer _userServer;

        // 完成依赖注入
        public KnowledgeServer(MySqlConnectionAdapter mysql,UserServer userServer)
        {
            _userServer = userServer;
            _logger = LogManager.GetCurrentClassLogger();
            _mysql = mysql;
        }

        // 功能:添加一个知识点到数据库
        // 参数:一个知识点的结构题代表知识点信息,一个httpContext用于获取当前用户的信息
        // 返回:执行成功返回数据库影响条数1,执行失败返回-1
        public int AddKnowledge(Knowledge knowledge, HttpContext httpContext)
        {
            _mysql.Open();

            // 从远程的redis中获取当前用户的信息
            User user = _userServer.GetUserInfoFromRedis(httpContext);

            if (user == null)
            {
                _mysql.Close();
                return -1;
            }

             string query = "insert into T_KNOWLEDGE_POINT(pk_id,pk_name,course_desc,teacher_id,create_time) " +
             "values(@pk_id,@pk_name,@course_desc,@teacher_id,@create_time)";


            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { "@pk_id", Guid.NewGuid() },
                { "@pk_name",knowledge.pk_name!},
                { "@course_desc",knowledge.course_desc!},
                { "@teacher_id",user.user_id},
                { "@create_time",DateTime.Now},

            };

            int count = _mysql.ExecuteNonQuery(query, parameters);

            if (count > 0)
            {
                _logger.Info($"添加了一个新的知识点:{knowledge.pk_name},本次花费了{_mysql.GetLastExecutionTime()}毫秒");
                _mysql.Close();
                return count;
            }
            else
            {
                _logger.Error($"添加知识点出现错误,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                _mysql.Close();
                return -1;
            }
        }
    
        // 功能:查询所有知识点
        // 参数:不需要参数
        // 返回：执行成功返回一个List<knowledge>里面包含了所有的知识点的数据
        // 额: 这里最好是要做分页处理,不过让我偷个懒吧
        public List<Knowledge> GetKnowledgeList() 
        {
            _mysql.Open();

            string query = "SELECT * FROM T_KNOWLEDGE_POINT";

            DataSet data = _mysql.ExecuteQuery(query);
            if (data == null || data.Tables[0].Rows.Count == 0)
            {
                _mysql.Close();
                // 查询出先错误
                _logger.Error($"查询所有知识点出错了,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                return null;
            }
            else
            {
                List<Knowledge> resultList = new List<Knowledge>();

                foreach (DataRow row in data.Tables[0].Rows)
                {
                    Knowledge  knowledge = new Knowledge();

                    knowledge.pk_id = row["pk_id"].ToString();
                    knowledge.pk_name = row["pk_name"].ToString();
                    knowledge.created_time =DateTime.Parse(row["create_time"].ToString());
                    knowledge.course_desc = row["course_desc"].ToString();
                    knowledge.teacher_id = Guid.Parse(row["teacher_id"].ToString());
                    resultList.Add(knowledge);
                }
                _mysql.Close();
                 return resultList;
            }
        }

        // 功能:通过一个知识点的id删除一个知识点
        // 参数:一个Guid是知识点的id
        // 返回:返回数据库影响条数1,执行失败返回-1
        public int DeleteKnowledge(Guid id)
        {
            _mysql.Open();
            string query = "Delete FROM T_KNOWLEDGE_POINT WHERE pk_id=@pk_id";


            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { "@pk_id", id },
            };

            int count = _mysql.ExecuteNonQuery(query, parameters);

            if (count > 0)
            {
                _logger.Info($"删除一个知识点,本次花费了{_mysql.GetLastExecutionTime()}毫秒");
                _mysql.Close();
                return count;
            }
            else
            {
                _logger.Error($"删除知识点出现错误,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                _mysql.Close();
                return -1;
            }
        }

        // 功能:对一个知识点数据进行修改
        // 参数:一个Knowledge里面包含了需要进行修改的数据
        // 返回:执行成功返回数据库影响条数1,执行失败返回-1
        public int ReviseKnowledge(Knowledge knowledge)
        {
            _mysql.Open();
            string query = "UPDATE T_KNOWLEDGE_POINT SET pk_name=@pk_name,course_desc=@course_desc WHERE pk_id=@pk_id";

            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { "@pk_id", knowledge.pk_id},
                { "@pk_name", knowledge.pk_name!},
                { "@course_desc", knowledge.course_desc!},
            };

            int count = _mysql.ExecuteNonQuery(query, parameters);

            if (count > 0)
            {
                _logger.Info($"修改了一个知识点,本次花费了{_mysql.GetLastExecutionTime()}毫秒");
                _mysql.Close();
                return count;
            }
            else
            {
                _logger.Error($"修改知识点出现错误,错误的sql语句:{_mysql.GetLastExecutedSql()},错误的信息:{_mysql.GetLastError()}");
                _mysql.Close();
                return -1;
            }
        }
    }
}
